package com.doudou.pay.helper.websocket;

import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor;

import com.doudou.pay.helper.entities.PayUser;
import com.doudou.pay.helper.entities.UserInfo;
import com.doudou.pay.helper.service.PayUserService;

@Component
public class HandshakeInterceptor extends HttpSessionHandshakeInterceptor {
	
	@Autowired
	private PayUserService payUserService;
	
	@Override
	public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler,
			Map<String, Object> attributes) throws Exception {
		
		String userId = ((ServletServerHttpRequest) request).getServletRequest().getParameter("userId");
		if(StringUtils.isEmpty(userId)) {
			return false;
		}
		
		String sessionKey = ((ServletServerHttpRequest) request).getServletRequest().getParameter("sessionKey");
		if(StringUtils.isEmpty(sessionKey)) {
			return false;
		}
		
		List<PayUser> payUser = payUserService.getPayUserByUserId(userId);
		if(null == payUser || payUser.size() == 0) {
			return false;
		}
		UserInfo userInfo = new UserInfo(sessionKey, userId);
		((ServletServerHttpRequest) request).getServletRequest().getSession().setAttribute("userInfo", userInfo);
		return super.beforeHandshake(request, response, wsHandler, attributes);
	}
	
	@Override
	public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler,
			Exception ex) {
		System.out.println("afterHandshake....");
		super.afterHandshake(request, response, wsHandler, ex);
	}
}
